package com.beiye.drivertransport.safelearn;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.frame.adapter.CommonAdapter;
import com.android.frame.adapter.ViewHolder;
import com.android.frame.view.linearlistview.LinearListView;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.SubActivity.SignDailyTrainingExamActivity;
import com.beiye.drivertransport.activity.TwoBaseAty;
import com.beiye.drivertransport.bean.CheckBean;
import com.beiye.drivertransport.bean.DaiKaoCourseBean;
import com.beiye.drivertransport.bean.DaikaoBean;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.config.AppInterfaceConfig;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.utils.LogUtils;
import com.beiye.drivertransport.utils.TiShiDialog;
import com.beiye.drivertransport.utils.UserManger;
import com.beiye.drivertransport.utils.Utils;
import com.githang.statusbar.StatusBarCompat;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

//日常培训考试列表
public class DailyTrainingExaminationItemActivity extends TwoBaseAty {


    ImageView img_dailyback;

    TextView tv_application;

    LinearListView lv_daikaotest;

    LinearListView lv_havetest;

    TextView tv_nodata;//待考试卷

    TextView tv_nodata1;//已考试卷
    List<DaikaoBean.RowsBean> finishnorows = new ArrayList<>();
    List<DaikaoBean.RowsBean> finishrows = new ArrayList<>();
    List<DaikaoBean.RowsBean> finishpassrows = new ArrayList<>();
    List<DaikaoBean.RowsBean> finishnopassrows = new ArrayList<>();
    private ExamationAdapter examationAdapter;
    private HaveExamationAdapter haveExamationAdapter;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};

    @Override
    public int getLayoutId() {
        return R.layout.activity_daily_training_examination_item;

    }

    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.img_dailyback) {
            finish();
        } else if (id == R.id.tv_application) {//申请考试
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(DailyTrainingExaminationItemActivity.this,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(DailyTrainingExaminationItemActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
                return;
            }
            if (tv_application.getText().toString().trim().equals("申请考试")) {
                SharedPreferences sp = getSharedPreferences("DailyTrainingExaminationItemActivity",
                        Context.MODE_PRIVATE);
                int qpSn = sp.getInt("qpSn", 0);
                int learnsn = sp.getInt("learnsn", 0);
                String orgId = sp.getString("orgId", "");
                LoginUserBean userInfo = UserManger.getUserInfo();
                LoginUserBean.DataBean data = userInfo.getData();
                String userId = data.getUserId();
                showLoadingDialog("");
                new Login().getApplyDailyTraining(userId, orgId, qpSn, learnsn, this, 2);//申请考试

            } else if (tv_application.getText().toString().trim().equals("继续考试")) {

                SharedPreferences sp = getSharedPreferences("DailyTrainingExaminationItemActivity",
                        Context.MODE_PRIVATE);
                int qpSn = sp.getInt("qpSn", 0);
                int learnsn = sp.getInt("learnsn", 0);
                int faceRecgMark = sp.getInt("faceRecgMark", 0);
                String photoUrl = sp.getString("photoUrl", "");
                //showLoadingDialog("");
                Bundle bundle = new Bundle();
                bundle.putInt("daikaosn", finishnorows.get(0).getSn());
                bundle.putInt("daikaoqpsn", qpSn);
                bundle.putInt("learnsn", learnsn);
                bundle.putInt("faceRecgMark", faceRecgMark);
                bundle.putString("photoUrl", photoUrl);
                startActivity(DailyTrainingExaminationActivity.class, bundle);
            }
        }

    }

    @Override
    public void initData() {
        img_dailyback = (ImageView) findViewById(R.id.img_dailyback);
        tv_application = (TextView) findViewById(R.id.tv_application);
        lv_daikaotest = (LinearListView) findViewById(R.id.lv_daikaotest);
        lv_havetest = (LinearListView) findViewById(R.id.lv_havetest);
        tv_nodata = (TextView)findViewById(R.id.tv_nodata);
        tv_nodata1 = (TextView)findViewById(R.id.tv_nodata1);

        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#1F80C4"));
        lv_daikaotest.setOnItemClickListener(new LinearListView.OnItemClickListener() {
            @Override
            public void onItemClick(LinearListView parent, View view, int position, long id) {
                if (Utils.isFastClicker()) {
                    return;
                }
                //检测是否有写的权限
                int permission = ActivityCompat.checkSelfPermission(DailyTrainingExaminationItemActivity.this,
                        "android.permission.WRITE_EXTERNAL_STORAGE");
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    // 没有写的权限，去申请写的权限，会弹出对话框
                    ActivityCompat.requestPermissions(DailyTrainingExaminationItemActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
                    return;
                }
                SharedPreferences sp = getSharedPreferences("DailyTrainingExaminationItemActivity",
                        Context.MODE_PRIVATE);
                int qpSn = sp.getInt("qpSn", 0);
                int learnsn = sp.getInt("learnsn", 0);
                int faceRecgMark = sp.getInt("faceRecgMark", 0);
                String photoUrl = sp.getString("photoUrl", "");
                showLoadingDialog("");
                Bundle bundle = new Bundle();
                bundle.putInt("daikaosn", examationAdapter.getItem(position).getSn());
                bundle.putInt("daikaoqpsn", qpSn);
                bundle.putInt("learnsn", learnsn);
                bundle.putInt("faceRecgMark", faceRecgMark);
                bundle.putString("photoUrl", photoUrl);
                startActivity(DailyTrainingExaminationActivity.class, bundle);
            }
        });
        lv_havetest.setOnItemClickListener(new LinearListView.OnItemClickListener() {
            @Override
            public void onItemClick(LinearListView parent, View view, int position, long id) {
                if (Utils.isFastClicker()) {
                    return;
                }
                SharedPreferences sp = getSharedPreferences("DailyTrainingExaminationItemActivity",
                        Context.MODE_PRIVATE);
                int qpSn = sp.getInt("qpSn", 0);
                Bundle bundle = new Bundle();
                bundle.putInt("havesn", haveExamationAdapter.getItem(position).getSn());
                bundle.putLong("havecreation", haveExamationAdapter.getItem(position).getCreationDate());
                bundle.putInt("haveqpsn", qpSn);
                bundle.putString("haveqptName", haveExamationAdapter.getItem(position).getQptName());
                bundle.putString("haveqpName", haveExamationAdapter.getItem(position).getQpName());
                bundle.putInt("havetotalScore", haveExamationAdapter.getItem(position).getTotalScore());
                bundle.putInt("havepassScore", haveExamationAdapter.getItem(position).getPassScore());
                bundle.putInt("havescore", haveExamationAdapter.getItem(position).getScore());
                bundle.putInt("havepassMark", haveExamationAdapter.getItem(position).getPassMark());
                bundle.putLong("testEndDate", haveExamationAdapter.getItem(position).getTestEndDate());
                bundle.putString("signPicUrl", haveExamationAdapter.getItem(position).getSignPicUrl());

                /**
                 * 此处要传这条已考的所有数据
                 */
                startActivity(HaveDailyTrainingExaminationActivity.class, bundle);
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        SharedPreferences sp = getSharedPreferences("DailyTrainingExaminationItemActivity",
                Context.MODE_PRIVATE);
        int qpSn = sp.getInt("qpSn", 0);
        int learnsn = sp.getInt("learnsn", 0);
        String orgId = sp.getString("orgId", "");
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        String userId = data.getUserId();
        showLoadingDialog("");
        new Login().getDailyTrainingDaikaoAndHave(userId, orgId, qpSn, learnsn, 2, 2, 1, 10000, this, 1);
    }

    @Override
    public void requestData() {
        Bundle bundle = getIntent().getExtras();
        String orgId = bundle.getString("orgId");
        int qpSn = bundle.getInt("qpSn");
        int learnsn = bundle.getInt("learnsn");
        LogUtils.e("测试", "requestData: "+learnsn );
        String photoUrl = bundle.getString("photoUrl");
        int faceRecgMark = bundle.getInt("faceRecgMark");
        SharedPreferences sp = getSharedPreferences("DailyTrainingExaminationItemActivity",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putInt("qpSn", qpSn);
        edit.putInt("learnsn", learnsn);
        edit.putString("orgId", orgId);
        edit.putString("photoUrl", photoUrl);
        edit.putInt("faceRecgMark", faceRecgMark);
        edit.commit();

        OkGo.get(AppInterfaceConfig.BASE_URL + "course/paper/" + qpSn)     // 请求方式和请求url
                .tag(this)                       // 请求的 tag, 主要用于取消对应的请求
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String result, Call call, Response response) {

                        DaiKaoCourseBean daiKaoCourseBean = JSON.parseObject(result, DaiKaoCourseBean.class);
                        DaiKaoCourseBean.DataBean databean = daiKaoCourseBean.getData();
                        int allowMuNo = databean.getAllowMuNo();
                        SharedPreferences sp = getSharedPreferences("DailyTrainingExaminationItemActivity",
                                Context.MODE_PRIVATE);
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putInt("allowMuNo", allowMuNo);
                        edit.commit();

                    }
                });

        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        String userId = data.getUserId();
        showLoadingDialog("");
        new Login().getDailyTrainingDaikaoAndHave(userId, orgId, qpSn, learnsn, 2, 2, 1, 10000, this, 1);
    }


    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
        if (what == 1) {
            tv_application.setVisibility(View.VISIBLE);
            dismissLoadingDialog();
            DaikaoBean daikaoBean = JSON.parseObject(result, DaikaoBean.class);
            List<DaikaoBean.RowsBean> daikaorows = daikaoBean.getRows();
            finishnorows.clear();
            finishrows.clear();
            for (int i = 0; i < daikaorows.size(); i++) {
                if (daikaorows.get(i).getFinishMark() == 0) {
                    finishnorows.add(daikaorows.get(i));
                } else {
                    finishrows.add(daikaorows.get(i));
                }

            }
            if (finishnorows.size() == 0)//判断待考是否有卷子
            {
                tv_nodata.setVisibility(View.VISIBLE);
            } else {
                tv_nodata.setVisibility(View.GONE);
            }
            if (finishrows.size() == 0)//判断已考是否有卷子
            {
                tv_nodata1.setVisibility(View.VISIBLE);
            } else {
                tv_nodata1.setVisibility(View.GONE);
            }

            finishpassrows.clear();
            finishnopassrows.clear();
            for (int i = 0; i < finishrows.size(); i++) {

                if (finishrows.get(i).getPassMark() == 1) {
                    finishpassrows.add(finishrows.get(i));
                } else {
                    finishnopassrows.add(finishrows.get(i));
                }

            }
            if (finishnorows.size() == 0) {
                if (finishpassrows.size() > 0)//及格判断
                {
                    tv_application.setVisibility(View.VISIBLE);
                    tv_application.setText("您考试已合格！");
                    tv_application.setEnabled(false);
                    tv_application.setBackgroundResource(R.drawable.notestbutton);//不可点击
                } else {//不及格判断
                    if (finishnopassrows.size() == 0) {
                        tv_application.setVisibility(View.VISIBLE);
                        tv_application.setText("申请考试");
                    } else {
                        SharedPreferences sp = getSharedPreferences("DailyTrainingExaminationItemActivity",
                                Context.MODE_PRIVATE);
                        int allowMuNo = sp.getInt("allowMuNo", 0);
                        if (allowMuNo < finishnopassrows.size() + 1) {
                            tv_application.setVisibility(View.VISIBLE);
                            tv_application.setText("您考试未合格，您本月需要重新学习！");
                            tv_application.setEnabled(false);
                            tv_application.setBackgroundResource(R.drawable.notestbutton);//不可点击
                        } else {
                            tv_application.setVisibility(View.VISIBLE);
                            tv_application.setText("申请考试");
                        }
                    }
                }

            } else {//有未完成卷子继续考试
                tv_application.setVisibility(View.VISIBLE);
                tv_application.setText("继续考试");
            }
            examationAdapter = new ExamationAdapter(DailyTrainingExaminationItemActivity.this, finishnorows, R.layout.testandexamiantion_item_layout1);
            lv_daikaotest.setAdapter(examationAdapter);
            haveExamationAdapter = new HaveExamationAdapter(DailyTrainingExaminationItemActivity.this, finishrows, R.layout.testandexamiantion_item_layout1);
            lv_havetest.setAdapter(haveExamationAdapter);
        } else if (what == 2) {
            dismissLoadingDialog();
            DaikaoBean daikaoBean = JSON.parseObject(result, DaikaoBean.class);
            Integer sn = daikaoBean.getData();//获取用户考卷系列号
            dismissLoadingDialog();
            SharedPreferences sp = getSharedPreferences("DailyTrainingExaminationItemActivity",
                    Context.MODE_PRIVATE);
            int qpSn = sp.getInt("qpSn", 0);
            int learnsn = sp.getInt("learnsn", 0);
            int faceRecgMark = sp.getInt("faceRecgMark", 0);
            String photoUrl = sp.getString("photoUrl", "");
            Bundle bundle = new Bundle();
            bundle.putInt("daikaosn", sn);
            bundle.putInt("daikaoqpsn", qpSn);
            bundle.putInt("learnsn", learnsn);
            bundle.putInt("faceRecgMark", faceRecgMark);
            bundle.putString("photoUrl", photoUrl);
            startActivity(DailyTrainingExaminationActivity.class, bundle);
        }
        super.onSuccess(result, call, response, what);
    }

    @Override
    public void onError(String result, Call call, Response response, int what) {
        if (what == 2) {
            dismissLoadingDialog();
            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
            //     int code = checkBean.getCode();
            String msg = checkBean.getMsg();
            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
            builder1.setMessage(msg);
            builder1.setTitle("提示:");
            builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    ;
                    //设置你的操作事项
                }
            });
            builder1.create().show();
        }
        super.onError(result, call, response, what);
    }

    public class ExamationAdapter extends CommonAdapter<DaikaoBean.RowsBean> {
        private Context context;
        private List<DaikaoBean.RowsBean> mList;

        public ExamationAdapter(Context context, List<DaikaoBean.RowsBean> mList, int itemLayoutId) {
            super(context, mList, itemLayoutId);
            this.context = context;
            this.mList = mList;
        }

        @Override
        public void convert(ViewHolder holder, DaikaoBean.RowsBean item, int positon) {
            TextView tv_testtitle = holder.getView(R.id.tv_testtitle);//日期
            TextView tv_time = holder.getView(R.id.tv_time);
            TextView tv_scon = holder.getView(R.id.tv_scon1);
            TextView tv_jige = holder.getView(R.id.tv_scon2);
            TextView tv_sign = holder.getView(R.id.tv_sign);

            if (mList.get(positon).getQpName() == null) {
                tv_testtitle.setText("");
            } else {

                tv_testtitle.setText(mList.get(positon).getQpName());
            }
            int finishMark = mList.get(positon).getFinishMark();
            if (finishMark == 1) {
                long creationDate = mList.get(positon).getCreationDate();
                //mill为你龙类型的时间戳
                if (creationDate > 0) {

                    Date date = new Date(creationDate);
                    String time = "";
                    try {
                        //yyyy表示年MM表示月dd表示日
                        //yyyy-MM-dd是日期的格式，比如2015-12-12如果你要得到2015年12月12日就换成yyyy年MM月dd日
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                        //进行格式化
                        time = sdf.format(date);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    tv_time.setText("考试时间:" + time);
                }
                int score = mList.get(positon).getScore();
                tv_scon.setText(score + "分");
                tv_scon.setTextColor(getResources().getColor(R.color.hidetroublenext));
                tv_jige.setVisibility(View.VISIBLE);
                int passMark = mList.get(positon).getPassMark();
                if (passMark == 1) {
                    tv_jige.setText("及格");
                    tv_jige.setTextColor(getResources().getColor(R.color.hiddengreen));
                    tv_sign.setVisibility(View.VISIBLE);
                } else {
                    tv_jige.setText("不及格");
                    tv_jige.setTextColor(getResources().getColor(R.color.holetotal_red));
                    tv_sign.setVisibility(View.GONE);
                }
            } else {
                tv_time.setText("考试时间:");
                tv_scon.setText("未完成考试");
                tv_scon.setTextColor(getResources().getColor(R.color.holetotal_red));
                tv_jige.setVisibility(View.GONE);
                tv_sign.setVisibility(View.GONE);
            }

//            final   int sn = mList.get(positon).getSn();
//            final  String signPicUrl = mList.get(positon).getSignPicUrl();
//
//            tv_sign.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    SharedPreferences sp = getSharedPreferences("DailyTrainingExaminationItemActivity",
//                            Context.MODE_PRIVATE);
//                    int learnsn = sp.getInt("learnsn", 0);
//                    Bundle bundle = new Bundle();
//                    bundle.putInt("sn", sn);
//                    bundle.putInt("learnsn", learnsn);
//                    bundle.putString("signPicUrl", signPicUrl);
//                    startActivity(SignDailyTrainingExamActivity.class, bundle);
//
//                }
//            });
        }


    }

    public class HaveExamationAdapter extends CommonAdapter<DaikaoBean.RowsBean> {
        private Context context;
        private List<DaikaoBean.RowsBean> mList;

        public HaveExamationAdapter(Context context, List<DaikaoBean.RowsBean> mList, int itemLayoutId) {
            super(context, mList, itemLayoutId);
            this.context = context;
            this.mList = mList;
        }

        @Override
        public void convert(ViewHolder holder, DaikaoBean.RowsBean item, int positon) {
            TextView tv_testtitle = holder.getView(R.id.tv_testtitle);//日期
            TextView tv_time = holder.getView(R.id.tv_time);
            TextView tv_scon = holder.getView(R.id.tv_scon1);
            TextView tv_jige = holder.getView(R.id.tv_scon2);
            TextView tv_sign = holder.getView(R.id.tv_sign);

            if (mList.get(positon).getQpName() == null) {
                tv_testtitle.setText("");
            } else {

                tv_testtitle.setText(mList.get(positon).getQpName());
            }
            int finishMark = mList.get(positon).getFinishMark();
            if (finishMark == 1) {
                long creationDate = mList.get(positon).getCreationDate();
                //mill为你龙类型的时间戳
                if (creationDate > 0) {

                    Date date = new Date(creationDate);
                    String time = "";
                    try {
                        //yyyy表示年MM表示月dd表示日
                        //yyyy-MM-dd是日期的格式，比如2015-12-12如果你要得到2015年12月12日就换成yyyy年MM月dd日
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                        //进行格式化
                        time = sdf.format(date);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    tv_time.setText("考试时间:" + time);
                }
                int score = mList.get(positon).getScore();
                tv_scon.setText(score + "分");
                tv_scon.setTextColor(getResources().getColor(R.color.hidetroublenext));
                tv_jige.setVisibility(View.VISIBLE);
                int passMark = mList.get(positon).getPassMark();
                if (passMark == 1) {
                    tv_jige.setText("及格");
                    tv_jige.setTextColor(getResources().getColor(R.color.hiddengreen));
                    tv_sign.setVisibility(View.VISIBLE);
                } else {
                    tv_jige.setText("不及格");
                    tv_jige.setTextColor(getResources().getColor(R.color.holetotal_red));
                    tv_sign.setVisibility(View.GONE);
                }
            } else {
                tv_time.setText("考试时间:");
                tv_scon.setText("未完成考试");
                tv_scon.setTextColor(getResources().getColor(R.color.holetotal_red));
                tv_jige.setVisibility(View.GONE);
                tv_sign.setVisibility(View.GONE);
            }

            final int sn = mList.get(positon).getSn();
            final String signPicUrl = mList.get(positon).getSignPicUrl();

            tv_sign.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SharedPreferences sp = getSharedPreferences("DailyTrainingExaminationItemActivity",
                            Context.MODE_PRIVATE);
                    int learnsn = sp.getInt("learnsn", 0);
                    Bundle bundle = new Bundle();
                    bundle.putInt("sn", sn);
                    bundle.putInt("learnsn", learnsn);
                    bundle.putString("signPicUrl", signPicUrl);
                    startActivity(SignDailyTrainingExamActivity.class, bundle);
                }
            });
        }


    }
}
